package io.github.fb513.api.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolConfig {

	@Bean
	public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties config){
		int coreSize = 0, maxSize = 10000, keepAliveTime = 120;
		String threadPoolNamePrefix = "im-api-";
		if (config != null) {
			if (config.getCoreSize() != null) {
				coreSize = config.getCoreSize();
			}
			if (config.getMaxSize() != null) {
				maxSize = config.getMaxSize();
			}
			if (config.getKeepAliveTime() != null) {
				keepAliveTime = config.getKeepAliveTime();
			}
			if (StringUtils.hasLength(config.getThreadPoolName())) {
				threadPoolNamePrefix = config.getThreadPoolName();
			}
		}
		return new ThreadPoolExecutor(coreSize, maxSize,
				keepAliveTime, TimeUnit.SECONDS,
				new SynchronousQueue<>(),
				Thread.ofVirtual().name(threadPoolNamePrefix, 0).factory(),
				new ThreadPoolExecutor.CallerRunsPolicy());
	}
}
